// 导入路由信息
import router, { constantRoutes, asyncRouters } from '@/router'
const state = () => {
  return {
    allRouters: constantRoutes
  }
}
const mutations = {
  setRouters(state, newRouter) {
    state.allRouters = newRouter
  }
}

const actions = {
  filterRouter(context) {
    // 获取用户可以访问的路由
    const _menus = context.rootState.user.userInfo.roles.menus
    // 筛选children 把符合的赋值给children属性
    const _newRouters = asyncRouters.filter(v => {
      const _length = v.children.filter(VC => {
        // 存在为true 直接return
        return _menus.includes(VC.name)
      }).length
      // 倒着说明过滤完了
      // 判断children的长度
      // 为0则没有符合的
      if (_length > 0) {
        return true
      } else {
        return false
      }
    })
    _newRouters.push(
      // 保证404在末尾
      { path: '*', redirect: '/404', hidden: true }
    )
    // 筛选完  再动态添加
    router.addRoutes(_newRouters)
    // 合并到vuex中
    context.commit('setRouters', [...constantRoutes, ..._newRouters])
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
